<?php

namespace app\modules\Admin\models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;

class upgradecodeModel extends Model
{
    protected $table = 'upgrade_code';
    protected $primaryKey = 'id';
    protected $appends = ['status_text', 'level_info', 'oper_name'];

    protected $hidden = [];


    protected static array $statuss = [
        'unused'=>'未使用',
        'used'=>'已使用',
        'disabed'=>'已禁用',
    ];

    /**
     * @param DateTimeInterface $date
     * @return string
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function getStatusTextAttribute()
    {
        $status_text = '';
        $status_key = array_keys(self::$statuss);
        if(in_array($this->attributes['status'], $status_key)){
            $status_text = self::$statuss[$this->attributes['status']];
        }
        unset($status_key);
        return $status_text;
    }


    public function getLevelInfoAttribute()
    {
        $level_info = [];
        if ($this->attributes['level']){
            $level = \agentlevelModel::query()->where('level', $this->attributes['level'])->select(['level', 'name', 'image'])->first();
            if ($level){
                $level_info = $level->toArray();
            }
        }
        return $level_info;
    }

    public function getOperNameAttribute()
    {
        $oper_name = '';
        if ($this->attributes['oper_id']){
            $oper_name = \adminModel::query()->where('id', $this->attributes['oper_id'])->value('username');
        }
        return $oper_name;
    }

    public function relationMember()
    {
        return $this->belongsTo(\memberModel::class, 'member_id_relation', 'id')->select(['id', 'phone', 'nickname', 'realname', 'avatar']);
    }

    public function useMember()
    {
        return $this->belongsTo(\memberModel::class, 'member_id_use', 'id')->select(['id', 'phone', 'nickname', 'realname', 'avatar']);
    }

    /**
     * @name 创建卡号
     * @description 返回结果最少4位  （不含0、不含O、不含i、不含L、）
     * @param int $length 默认8位，最少4位
     * @return string
     */
    public static function createSn(int $length = 8): string
    {
        $codeSn = '';
        $length = ($length > 4)?$length:4;
        $characters = '123456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ';
        for ($i = 0; $i < $length; $i++) {
            $codeSn .= $characters[rand(0, strlen($characters) - 1)];
        }
        if(self::query()->where('code', $codeSn)->exists()){
            $codeSn = self::createSn($length);
        }
        return $codeSn;
    }
}